<template>
  <div style="width: 100%; height: 100%; position: relative">
    <el-carousel
      v-if="state.carouselItems.length > 0"
      :direction="'horizontal'"
      :loop="true"
      arrow="hover"
      :lazy="false"
      indicator-position="none"
      trigger="hover"
      :autoplay="false"
      @change="handleCarouselChange"
      class="video-carousel"
      ref="carouselRef"
    >
      <el-carousel-item
        v-for="(item, index) in state.carouselItems"
        :key="index"
      >
        <!-- 单窗口模式 -->

        <div
          v-if="activeView === 'one'"
          class="video-container"
          :class="{ 'active-border': currentIndex === index }"
          :data-key="index"
          @click="handleItemClick(index)"
        >
          <div
            v-if="!hasVideoStream(index)"
            class="no-video-placeholder"
            style="z-index: 10000"
          >
            <el-icon class="no-video-icon"><Plus /></el-icon>
            <p>暂无视频流</p>
          </div>
          <div
            :id="`player-${index}`"
            class="video-play"
            @click="handleItemClick2(index)"
          ></div>
        </div>

        <!-- 四窗口模式 -->
        <div v-if="activeView === 'four'" class="video-grid">
          <div
            v-for="(subItem, subIndex) in item"
            :key="subIndex"
            class="video-item"
            :class="{
              'active-border':
                currentIndex === index && currentSubIndex === subIndex,
            }"
            @click="handleItemClick(index, subIndex)"
            :data-key="`${index}-${subIndex}`"
          >
            <div class="video-placeholder-container">
              <div
                class="no-video-placeholder"
                style="z-index: 10000"
                v-if="!hasVideoStream(index, subIndex)"
              >
                <el-icon class="no-video-icon"><Plus /></el-icon>
                <p>暂无视频流</p>
              </div>
              <div
                :id="`player-${index}-${subIndex}`"
                @click="handleItemClick2(index, subIndex)"
                class="video-play"
              ></div>
            </div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <div class="no-video" v-else>
      <el-icon class="no-video-icon"><Plus /></el-icon>
      <p>暂无视频流</p>
    </div>

    <!-- 视频控制栏 - 仅当前选中项显示 -->
    <div class="video-controls" v-if="showControls">
      <!-- 声音控制 -->
      <div class="sound-control">
        <img
          src="@/assets/images/xgjd/kqshengyin.png"
          alt="关闭声音"
          @click="handleSoundToggle"
          v-if="!isMuted"
        />
        <img
          src="@/assets/images/xgjd/gb.png"
          alt="开启声音"
          @click="handleSoundToggle"
          v-if="isMuted"
        />
      </div>

      <!-- 截图 -->
      <img
        src="@/assets/images/xgjd/jietu.png"
        alt="截图"
        @click="handleCapture"
      />

      <!-- 录像控制 -->
      <div class="record-control">
        <img
          src="@/assets/images/xgjd/luxiang.png"
          alt="开始录像"
          @click="handleRecordToggle"
          v-if="!isRecording"
        />
        <img
          src="@/assets/images/xgjd/jsluxiang.png"
          alt="结束录像"
          @click="handleRecordToggle"
          v-if="isRecording"
        />
      </div>

      <!-- 清晰度切换 -->
      <el-dropdown placement="top" @command="handleResolutionChange">
        <el-button size="mini" class="resolution-btn">
          {{ currentResolution }}
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="1">标清</el-dropdown-item>
            <el-dropdown-item command="0">高清</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 更多---跳转详情 -->
      <div class="canel" @click="handleBack">
        <span> 详情</span>
        <!-- <img src="@/assets/images/xgjd/gengduo.png" alt="gengduo" /> -->
      </div>
    </div>

    <!-- 底部控制栏 -->
    <div class="footer">
      <img
        src="@/assets/images/xgjd/close.png"
        alt="关闭"
        @click="closeVideo"
      />
      <span>
        <span v-if="state.carouselItems.length > 0">
          {{ currentIndex + 1 }}
        </span>
        <span v-else>0</span>
        / {{ state.carouselItems.length }}
      </span>
      <img
        src="@/assets/images/xgjd/screenshot.png"
        alt="横屏"
        @click="handleScreenRotation"
      />
    </div>
  </div>
</template>

<script setup>
import { getPointUrl, getPointUrlBack, talkToseppk } from "@/api/event.js";
import { getwithdrawtransferinfo } from "@/api/videoplan.js";
import dayjs from "dayjs";
import { useUserStore } from "@/pinia/user.js";
import { useRouter } from "vue-router";
import {
  onMounted,
  onBeforeUnmount,
  watch,
  reactive,
  ref,
  nextTick,
} from "vue";
import { Plus } from "@element-plus/icons-vue";

const router = useRouter();
const piniaUser = useUserStore();
const emit = defineEmits(["showql", "itemClick"]);
const props = defineProps({
  vid: String,
  Times: String,
  activeView: String,
  showtab: {
    type: Boolean,
    default: true,
  },
});

// 状态管理
const state = reactive({
  playerInstances: {}, // 多播放器实例管理
  curIndex: 0, // 当前窗口索引
  carouselItems: [], // 轮播项数据
  videoStreamStatus: {}, // 记录视频流状态 { "index-subIndex": true/false }
  showPlaceholder: {}, // 新增：控制占位符显示的状态
  loading: {}, // 新增：加载状态管理（关键修复点）
});

// 响应式变量
const playStatus = ref(true);
const deviceIds = ref([]);
const currentIndex = ref(0); // 轮播当前索引
const currentSubIndex = ref(0); // 子窗口当前索引
const isPlayerInitialized = ref(false); // 标记播放器是否已初始化
const carouselRef = ref(null); // 轮播组件引用
const showControls = ref(false); // 控制栏显示状态
const isMuted = ref(false); // 声音状态
const isRecording = ref(false); // 录像状态
const isTalking = ref(false); // 对讲状态
const currentResolution = ref("标清"); // 当前清晰度

const autoHideTimer = ref(null); // 新增定时器变量
// 检查是否有视频流
const hasVideoStream = (index, subIndex = null) => {
  const key = subIndex !== null ? `${index}-${subIndex}` : `${index}`;
  // 优先判断视频流是否真的存在（videoStreamStatus 由播放结果决定）
  if (state.videoStreamStatus[key] === false) return false;
  // showPlaceholder 仅用于“主动关闭后显示占位符”的场景
  return !state.showPlaceholder[key];
};

let isFullScreen = ref(false); // 全屏状态标记
// 横屏查看（当前选中窗口全屏）
const handleScreenRotation = () => {
  isFullScreen.value = !isFullScreen.value; // 切换全屏状态
  // 显示控制栏（如果是进入横屏）
  if (isFullScreen.value) {
    showControls.value = true;

    // 清除之前的定时器
    if (autoHideTimer.value) {
      clearTimeout(autoHideTimer.value);
    }

    // 设置3秒后自动隐藏
    autoHideTimer.value = setTimeout(() => {
      showControls.value = false;
    }, 3000);
  } else {
    // 退出横屏时不自动隐藏
    document.documentElement.classList.remove("video-fullscreen");
    emit("screenRotation", false);
  }
  if (!isFullScreen.value) {
    // 退出全屏
    document.documentElement.classList.remove("video-fullscreen");
    emit("screenRotation", false); // 触发自定义事件，传递竖屏状态
    nextTick(() => {
      setTimeout(() => {
        resize();
      }, 50);
    });
    return;
  } else {
    document.documentElement.classList.add("video-fullscreen");
    emit("screenRotation", true); // 触发自定义事件，传递横屏状态
    nextTick(() => {
      setTimeout(() => {
        resize();
      }, 50);
    });

    return;
  }
};

// 双击跳转详情
let clickCount = ref(0);
const handleItemClick2 = async (index, subIndex = null) => {
  console.log("双击", index, subIndex);
  clickCount.value++;

  console.log("props.activeView", props.activeView);
  if (clickCount.value === 2) {
    currentIndex.value = index;
    if (subIndex !== null) {
      currentSubIndex.value = subIndex;
    }
    let targetId;
    if (props.activeView === "one") {
      targetId = state.carouselItems[currentIndex.value]?.id;
    } else {
      targetId =
        state.carouselItems[currentIndex.value]?.[currentSubIndex.value]?.id;
    }

    console.log("handleItemClick2------------", targetId);
    router.push({
      name: "webviewVideo",
      query: {
        indexCode: targetId,
      },
    });
    clickCount.value = 0; // 归零
  }

  //延迟1s清0
  setTimeout(() => {
    clickCount.value = 0;
  }, 1000);
};

// 处理Item点击 -支持单击
const handleItemClick = async (index, subIndex = null) => {
  // 执行原单击逻辑
  currentIndex.value = index;
  if (subIndex !== null) {
    currentSubIndex.value = subIndex;
  }
  showControls.value = !showControls.value;

  let targetId;
  if (props.activeView === "one") {
    targetId = state.carouselItems[currentIndex.value]?.id;
  } else {
    targetId =
      state.carouselItems[currentIndex.value]?.[currentSubIndex.value]?.id;
  }

  if (targetId) {
    emit("itemClick", targetId);
  } else {
    emit("itemClick", "");
  }

  // 当用户主动点击时，重置自动隐藏定时器
  if (isFullScreen.value) {
    showControls.value = true;

    // 清除之前的定时器
    if (autoHideTimer.value) {
      clearTimeout(autoHideTimer.value);
    }

    // 重新设置3秒后自动隐藏
    autoHideTimer.value = setTimeout(() => {
      showControls.value = false;
    }, 3000);
  }
};

// 处理关闭事件---关闭当前并显示占位符
const closeVideo = async () => {
  const windowIndex = getCurrentWindowIndex();
  const player = getCurrentPlayer();

  // 获取当前键值（需要传入索引）
  const key =
    props.activeView === "one"
      ? getPlayerKey(currentIndex.value)
      : getPlayerKey(currentIndex.value, currentSubIndex.value);

  if (player && windowIndex !== null) {
    try {
      await player.JS_StopRealPlayAll();
      const container = document.getElementById(`player-${key}`);
      if (container) container.style.display = "none";
    } catch (err) {
      console.error("停止播放失败", err);
    }
  }

  // 更新状态管理
  state.videoStreamStatus[key] = false;
  state.showPlaceholder[key] = true;
};

// 增播放器key生成方法

const getPlayerKey = (index, subIndex = null) => {
  return subIndex !== null ? `${index}-${subIndex}` : `${index}`;
};
// 1. 声音控制切换（仅操作当前窗口）
const handleSoundToggle = () => {
  console.log("声音控制切换");
  // 解决 “无效操作” 的问题，避免因窗口未就绪 / 不存在导致的错误。
  const windowIndex = getCurrentWindowIndex();
  console.log("windowIndex", windowIndex);
  const player = getCurrentPlayer();
  console.log("player", !windowIndex || !player);
  // if (!windowIndex || !player) return;
  console.log("isMuted.value", isMuted.value);
  if (isMuted.value) {
    console.log("开启声音");
    // 开启当前窗口声音（h5player接口：JS_OpenSound）
    player
      .JS_OpenSound(windowIndex)
      .then(() => {
        isMuted.value = false;
        console.log(`窗口${windowIndex}开启声音成功`);
      })
      .catch((err) => {
        console.error(`窗口${windowIndex}开启声音失败`, err);
        // 错误处理：如提示"当前窗口无音频流"（对应错误码0x12f910014）
        if (err.code === 0x12f910014) {
          console.error("当前视频无音频数据");
          // ElMessage.warning("当前视频无音频数据");
        }
      });
  } else {
    // 关闭当前窗口声音（h5player接口：JS_CloseSound）
    player
      .JS_CloseSound(windowIndex)
      .then(() => {
        isMuted.value = true;
        console.log(`窗口${windowIndex}关闭声音成功`);
      })
      .catch((err) => {
        console.error(`窗口${windowIndex}关闭声音失败`, err);
      });
  }
};

// 2. 截图功能（仅对当前窗口截图）

const handleCapture = () => {
  const windowIndex = getCurrentWindowIndex();
  const player = getCurrentPlayer();

  // 生成唯一文件名（包含窗口索引和时间戳）
  const fileName = `capture-win${windowIndex}-${dayjs().format(
    "YYYYMMDDHHmmss"
  )}.jpg`;

  player
    .JS_CapturePicture(windowIndex, fileName, "JPEG", (imageData) => {
      try {
        // 将Base64转换为Blob
        const byteString = atob(imageData.split(",")[1]);
        const mimeString = imageData.split(",")[0].split(":")[1].split(";")[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);

        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }

        const blob = new Blob([ab], { type: mimeString });

        // 创建下载链接
        const downloadUrl = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理资源
        setTimeout(() => {
          document.body.removeChild(link);
          URL.revokeObjectURL(downloadUrl);
        }, 100);

        console.log(`窗口${windowIndex}截图成功，已保存为：${fileName}`);
      } catch (error) {
        console.error("截图处理失败：", error);
      }
    })
    .catch((err) => {
      console.error(`窗口${windowIndex}截图失败`, err);
      if (err.code === 0x12f930011) {
        console.error("视频未加载完成，请稍后重试");
      }
    });
};
// 3. 云台控制跳转
const handlePTZ = () => {
  console.log("云台控制跳转");
  const targetId = getCurrentDeviceId();
  console.log("targetId", targetId);
  if (targetId) {
    // 先判断是否处于横屏状态，如果是则退出横屏
    if (isFullScreen.value) {
      // 移除全屏类名
      document.documentElement.classList.remove("video-fullscreen");
      // 通知父组件退出横屏
      emit("screenRotation", false);
      // 重置全屏状态标记
      isFullScreen.value = false;
      // 触发一次resize确保视频显示正常
      resize();
    }
    router.push({
      name: "webviewVideo",
      query: {
        indexCode: targetId,
        streamType: currentResolution.value === "标清" ? "1" : "0",
      },
    });
  }
};

// 4. 对讲功能
const handleTalk = () => {
  console.log("对讲功能");
  const targetId = getCurrentDeviceId();
  const player = getCurrentPlayer();
  if (!targetId || !player) return;

  if (isTalking.value) {
    // 停止对讲
    player
      .JS_StopTalk()
      .then(() => {
        isTalking.value = false;
        console.log("已停止对讲");
      })
      .catch((err) => {
        console.error("停止对讲失败", err);
      });
  } else {
    // 获取对讲URL并开始对讲（h5player要求必须在HTTPS环境）
    talkToseppk({ deviceId: targetId, role: piniaUser.user.role })
      .then(({ data }) => {
        if (data.url) {
          player
            .JS_StartTalk(data.url)
            .then(() => {
              isTalking.value = true;
              console.log("开始对讲");
            })
            .catch((err) => {
              console.error("开始对讲失败", err);
              // 错误处理：如非HTTPS环境（h5player限制）
              if (err.code === 0x12f950000) {
                console.error("对讲功能仅支持HTTPS环境");
              }
            });
        }
      })
      .catch((err) => {
        console.error("获取对讲URL失败", err);
      });
  }
};
// 5. 录像功能切换
const handleRecordToggle = () => {
  console.log("录像功能切换");
  const windowIndex = getCurrentWindowIndex();
  const player = getCurrentPlayer();
  // if (!windowIndex || !player) return;

  if (isRecording.value) {
    // 停止当前窗口录像并保存
    player
      .JS_StopSave(windowIndex)
      .then(() => {
        isRecording.value = false;
        console.log("录像已保存");
        console.log(`窗口${windowIndex}停止录像成功`);
      })
      .catch((err) => {
        console.error(`窗口${windowIndex}停止录像失败`, err);
        // 错误处理：如未开启录像却调用停止（错误码0x12f920016）
        if (err.code === 0x12f920016) {
          console.error("未开启录像，无法停止");
        }
      });
  } else {
    // 开始当前窗口录像（MP4格式，文件名含窗口索引）
    const fileName = `record-win${windowIndex}-${dayjs().format(
      "YYYYMMDDHHmmss"
    )}`;
    console.log("开始录像", fileName);
    player
      .JS_StartSaveEx(windowIndex, fileName, 5) // 5表示MP4格式
      .then(() => {
        isRecording.value = true;
        console.log("开始录像");
        console.log(`窗口${windowIndex}开始录像成功`);
      })
      .catch((err) => {
        console.error(`窗口${windowIndex}开始录像失败`, err);
        // 错误处理：如未停止录像却重复开启（错误码0x12f920015）
        if (err.code === 0x12f920015) {
          console.error("已在录像中，请先停止当前录像");
        }
      });
  }
};

// 6. 清晰度切换
const handleResolutionChange = (command) => {
  console.log("清晰度切换", command);
  const resolutionMap = { 1: "标清", 0: "高清" };
  currentResolution.value = resolutionMap[command];
  console.log("切换清晰度：", currentResolution.value);
  const windowIndex = getCurrentWindowIndex();
  if (windowIndex !== null) {
    // 停止当前窗口播放（避免流冲突）
    const player = getCurrentPlayer();
    player?.JS_StopRealPlayAll();
    // 重新播放并传入当前清晰度对应的streamType
    play(windowIndex);
  }
};

// 7.返回---跳转页面
const handleBack = () => {
  // 获取当前活跃窗口的设备ID
  const currentId = getCurrentDeviceId();
  console.log("handleBac----------------k", currentId);
  router.push({
    name: "webviewVideo",
    query: {
      indexCode: currentId,
    },
  });
};
// 获取当前窗口的索引
const getCurrentWindowIndex = () => {
  if (props.activeView === "one") {
    // 单窗口模式：当前轮播项索引即为窗口索引
    return currentIndex.value;
  } else if (props.activeView === "four") {
    // 四窗口模式：子窗口索引为实际操作窗口索引
    return currentSubIndex.value;
  }
  return null;
};

// 获取当前设备ID
const getCurrentDeviceId = () => {
  console.log("props.activeView", props.activeView);
  if (props.activeView === "one") {
    return state.carouselItems[currentIndex.value]?.id;
  } else {
    return state.carouselItems[currentIndex.value]?.[currentSubIndex.value]?.id;
  }
};

// 获取当前播放器实例
const getCurrentPlayer = () => {
  const key =
    props.activeView === "one"
      ? `${currentIndex.value}`
      : `${currentIndex.value}-${currentSubIndex.value}`;
  console.log("playerInstances 结构：", state.playerInstances);
  console.log("当前 key：", key, "对应实例：", state.playerInstances[key]);
  return state.playerInstances[key];
};

// 手动切换轮播
const prevSlide = () => {
  if (carouselRef.value) {
    carouselRef.value.prev();
  }
};
const nextSlide = () => {
  if (carouselRef.value) {
    carouselRef.value.next();
  }
};

// 初始化轮播数据
const initCarouselData = () => {
  console.log("初始化轮播数据");
  if (deviceIds.value.length === 0) return;
  console.log("初始化轮播数据");
  state.videoStreamStatus = {};
  state.showPlaceholder = {}; // 初始化占位符状态

  if (props.activeView === "one") {
    state.carouselItems = deviceIds.value.map((id, index) => {
      state.videoStreamStatus[index] = false;
      state.showPlaceholder[index] = false; // 初始不显示占位符
      return { id };
    });
  } else if (props.activeView === "four") {
    const group = [];
    let temp = [];
    deviceIds.value.forEach((id, index) => {
      const subIndex = temp.length;
      const key = `${group.length}-${subIndex}`;
      state.videoStreamStatus[key] = false;
      state.showPlaceholder[key] = false; // 初始不显示占位符
      temp.push({ id });
      if ((index + 1) % 4 === 0) {
        group.push(temp);
        temp = [];
      }
    });
    if (temp.length > 0) group.push(temp);
    state.carouselItems = group;
  }

  console.log("初始化轮播数据deviceIds:", deviceIds.value);
  console.log("初始化轮播数据生成的carouselItems:", state.carouselItems);
};

// 切换播放/回放
const changeVideo = () => {
  playStatus.value = !playStatus.value;
  if (playStatus.value) {
    play();
  } else {
    playBack();
  }
};

// 回放功能
const playBack = async (windowIndex = 0) => {
  // 原有逻辑保持不变
  let targetId;
  if (props.activeView === "one") {
    targetId = state.carouselItems[currentIndex.value]?.id;
  } else {
    targetId = state.carouselItems[currentIndex.value]?.[windowIndex]?.id;
  }
  if (!targetId) return;

  const bt = dayjs(new Date(props.Times))
    .subtract(10, "second")
    .format("YYYY-MM-DDTHH:mm:ss.SSSZ");
  const et = dayjs(new Date(props.Times))
    .add(10, "second")
    .format("YYYY-MM-DDTHH:mm:ss.SSSZ");

  try {
    const { data } = await getPointUrlBack({
      cameraId: targetId,
      beginTime: bt,
      endTime: et,
      uuid: "",
    });
    if (data.url) {
      const key =
        props.activeView === "one"
          ? `${currentIndex.value}`
          : `${currentIndex.value}-${windowIndex}`;
      state.videoStreamStatus[key] = true;
      const player = getCurrentPlayer();
      if (player) {
        player
          .JS_Play(
            data.url,
            { playURL: data.url, mode: 1 },
            windowIndex,
            bt,
            et
          )
          .then(() => resize());
      }
    }
  } catch (e) {
    console.error("回放失败", e);
  }
};

// 实时播放
const play = async (index, subIndex = null) => {
  let targetId;
  if (props.activeView === "one") {
    targetId = state.carouselItems[index]?.id;
  } else {
    targetId = state.carouselItems[index]?.[subIndex]?.id;
  }
  if (!targetId) return;

  const key = getPlayerKey(index, subIndex);
  const container = document.getElementById(`player-${key}`);
  if (container) container.style.display = "block";

  state.videoStreamStatus[key] = true;
  state.showPlaceholder[key] = false;

  try {
    const { data } = await getPointUrl({
      deviceIds: [targetId],
      ifwww: "1",
      streamType: currentResolution.value === "标清" ? "1" : "0",
    });
    const urls = data.cameraUrls || [];

    if (urls.length > 0) {
      const player = state.playerInstances[key];
      if (player) {
        player.JS_StopRealPlayAll();

        // 修复：单画面模式使用窗口索引0
        const windowIndex = props.activeView === "one" ? 0 : subIndex;

        player
          .JS_Play(
            urls[0].cameraUrl,
            { playURL: urls[0].cameraUrl, mode: 1 },
            windowIndex
          )
          .then(() => resize());
      }
    }
  } catch (e) {
    console.error("播放失败", e);
    state.videoStreamStatus[key] = false;
    state.showPlaceholder[key] = true;
  }
};

// 初始化播放器
const initPlayer = async () => {
  isPlayerInitialized.value = false;
  deviceIds.value = [];
  state.playerInstances = {};
  state.videoStreamStatus = {};
  try {
    const res = await getwithdrawtransferinfo({ transId: props.vid });
    deviceIds.value = res.data.deviceIds || [];
    initCarouselData();

    // 等待 DOM 渲染完成
    await nextTick();

    if (props.activeView === "one") {
      // 修复：只初始化当前轮播项（索引0）
      await initPlayerInstance(0);
      play(0);
    } else {
      // 修复：只初始化第一页的四画面
      for (let j = 0; j < state.carouselItems[0].length; j++) {
        await initPlayerInstance(0, j);
        play(0, j);
      }
    }
  } catch (e) {
    console.error("初始化播放器失败", e);
  }
};

// 初始化播放器事件
const initPlayerEvents = (player, index) => {
  player.JS_SetWindowControlCallback({
    windowEventSelect: (i) => {
      state.curIndex = i;
      if (props.activeView === "four") currentSubIndex.value = i;
    },
    pluginErrorHandler: (iWndIndex, iErrorCode) => {
      console.error(`窗口${iWndIndex}错误，代码：${iErrorCode}`);
      const key =
        props.activeView === "one"
          ? `${currentIndex.value}`
          : `${currentIndex.value}-${iWndIndex}`;
      state.videoStreamStatus[key] = false;
      play(iWndIndex);
    },
    // 全屏
    windowFullCcreenChange: (bFull) => {
      // 全屏状态切换时更新根元素类名
      if (bFull) {
        document.documentElement.classList.add("video-fullscreen");
      } else {
        document.documentElement.classList.remove("video-fullscreen");
      }
      // 调整大小适配
      setTimeout(() => resize(), 50);
    },
  });
};

// 销毁播放器
const destroyPlayer = () => {
  Object.values(state.playerInstances).forEach((player) => {
    player?.JS_StopRealPlayAll();
    player?.JS_DestroyWorker();
  });
  // 清空实例和状态
  state.playerInstances = {};
  state.videoStreamStatus = {};
  state.showPlaceholder = {};
  isPlayerInitialized.value = false;
};

// 窗口大小调整
const resize = () => {
  Object.entries(state.playerInstances).forEach(([key, player]) => {
    const pid = props.activeView === "one" ? `player-${key}` : `player-${key}`; // 直接使用 key 拼接，因为 key 本身就是如 "0-0" 这样的格式
    const domElement = document.getElementById(pid);
    // debugger
    // 确保播放器和 DOM 都有效
    if (player && domElement) {
      setTimeout(() => player.JS_Resize(), 50);
    }
  });
};
// 初始化播放器实例
const initPlayerInstance = (index, subIndex = null) => {
  return new Promise((resolve) => {
    nextTick(() => {
      const key = getPlayerKey(index, subIndex);
      const pid = `player-${key}`;
      const domElement = document.getElementById(pid);

      if (!domElement) {
        console.error(`DOM 元素 ${pid} 未找到，跳过初始化`);
        resolve(false);
        return;
      }

      if (!state.playerInstances[key]) {
        state.playerInstances[key] = new JSPlugin({
          szId: pid,
          szBasePath: "/js/",
          bSupporDoubleClickFull: false,
          iMaxSplit: 1,
          iCurrentSplit: 1,
          bBlockEvent: false,
        });

        // 修复：为单画面模式也初始化事件
        // 无论单画面还是四画面，都需要初始化事件
        initPlayerEvents(
          state.playerInstances[key],
          subIndex !== null ? subIndex : 0
        );
      }
      resolve(true);
    });
  });
};
// 轮播图切换
const handleCarouselChange = async (index) => {
  currentIndex.value = index;
  currentSubIndex.value = 0;
  showControls.value = false;

  // 根据模式初始化新项
  if (props.activeView === "one") {
    await initPlayerInstance(index);
    play(index);
  } else {
    for (let j = 0; j < state.carouselItems[index].length; j++) {
      await initPlayerInstance(index, j);
      play(index, j);
    }
  }

  // 取当前轮播项的targetId并触发itemClick事件
  let targetId;
  if (props.activeView === "one") {
    targetId = state.carouselItems[currentIndex.value]?.id;
  } else {
    targetId =
      state.carouselItems[currentIndex.value]?.[currentSubIndex.value]?.id;
  }

  if (targetId) {
    emit("itemClick", targetId); // 触发事件，与handleItemClick保持一致
  } else {
    emit("itemClick", "");
  }
  console.log("切换轮播项", targetId);
};
// 监听属性变化
watch(
  () => props.vid,
  (newVal) => {
    if (newVal) {
      initPlayer();
    }
  },
  { immediate: true }
);

watch(
  () => props.activeView,
  (newView) => {
    initPlayer();
  }
);

// 生命周期
onMounted(() => {
  window.addEventListener("resize", resize);
});

onBeforeUnmount(() => {
  destroyPlayer();
  window.removeEventListener("resize", resize);
  if (autoHideTimer.value) {
    clearTimeout(autoHideTimer.value);
  }
});

// 暴露方法
defineExpose({
  resize,
  // startTalk,
  // stopTalk,
  // zoom,
  changeVideo,
  prevSlide,
  nextSlide,
});
</script>

<style lang="scss" scoped>
::v-deep {
  // 基础iPad适配（覆盖768px到1366px宽度范围）
  @media only screen and (min-width: 768px) and (max-width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 768px) and (max-width: 1366px) and (min-device-pixel-ratio: 1.5) {
    // 单窗口模式下的视频高度调整
    .video-container {
      height: calc(100% - 40px) !important;
    }

    // 四窗口模式下的单个视频高度调整
    .video-item {
      height: 40vh !important;
    }
    // 按钮的高度
    .video-controls {
      bottom: 3.5% !important;
    }
    // 全屏状态下的适配
    .video-fullscreen {
      .video-container {
        height: calc(100vw - 100px) !important;
      }
      .video-item {
        height: calc(50vh - 60px) !important;
      }
    }
  }

  // 针对大尺寸iPad Pro横屏的额外适配
  @media only screen and (min-width: 1024px) and (max-width: 1366px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 1024px) and (max-width: 1366px) and (orientation: landscape) and (min-device-pixel-ratio: 1.5) {
    .video-container {
      height: calc(100% - 20px) !important;
    }
    // 按钮的高度
    .video-controls {
      bottom: 3.5% !important;
    }
    .video-item {
      height: 40vh !important;
    }
  }

  // 针对iPad竖屏的特殊适配
  @media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) and (min-device-pixel-ratio: 1.5) {
    .video-container {
      height: calc(100% - 30px) !important;
    }
    // 按钮的高度
    .video-controls {
      bottom: 3.5% !important;
    }
    .video-item {
      height: 40vh !important;
    }
  }
}

.video-carousel {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  overflow-y: auto;
  ::v-deep .el-carousel__container {
    height: 100%;
  }
}

.video-container,
.video-item {
  padding: 4px;
  box-sizing: border-box;
  pointer-events: auto;
}

.video-container {
  width: 100%;
  height: 100%;
}

.video-grid {
  height: calc(100% - 160px);
  padding: 4px;
  overflow-y: auto;
}

.video-item {
  flex: 1;
  width: 100%;
  // box-sizing: border-box;
  // 计算高度，和单宫格模式下 video-container 高度一致
  height: 250px;
  margin: 5px 0;
  position: relative;
  // height: calc(100% / 4);
}

.video-play {
  width: 100%;
  height: 100%;
  // background: #000;
  position: relative;
  overflow: hidden;
}
.video-play.hidden {
  display: none !important;
}
.video-placeholder-container {
  position: relative;
  width: 100%;
  height: 100%;
}

// 无视频流占位样式
.no-video-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  background: #5f5f5f !important;
  z-index: 5;
  pointer-events: none;
  p {
    color: #ffffff;
  }
  ::v-deep .no-video-icon {
    // 使用::v-deep穿透scoped，确保图标样式生效
    font-size: 36px;
    margin-bottom: 10px;
    color: #fff; // 图标颜色
  }
}

.no-video {
  position: absolute;
  top: 0%;
  left: 0;
  width: 100%;
  height: 90%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  background: #5f5f5f;
  z-index: 1;
}

.active-border {
  // border: 2px solid #ffb03f;
  // border-radius: 4px;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  gap: 100px;
  background: #1c1b1b;
  color: white;
  z-index: 100;
  padding: 0 20px;
}

.footer img {
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.video-controls {
  width: 100%;
  height: 60px;
  z-index: 100;
  background: #1c1b1b;
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  bottom: 5.5%;

  .sound-control {
    display: flex;
  }
  .record-control {
    display: flex;
  }
  .canel {
    display: flex;
    span {
      display: flex;
      color: #ffffff;
    }
  }
  img {
    width: 30px;
    height: 30px;
  }
  .clear {
    background: #ffffff;
    span {
      display: flex;
      align-items: center;
      font-size: 12px;
      padding: 2px 5px;
    }
  }
}

// 全屏状态根元素样式
// 全屏横向布局核心样式
.video-fullscreen {
  // 轮播容器全屏化
  .video-carousel {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    // width: 100vw !important;
    // height: 100vh !important;
    z-index: 99999 !important;
    background: #1c1b1b !important;

    // 顺时针旋转90度，使轮播横向"转动"
    transform: rotate(90deg);
    // 调整旋转中心为容器中心（避免旋转后偏移）
    transform-origin: center;
    // 旋转后可能需要调整尺寸以填满屏幕
    width: 100vh !important; // 用视口高度作为宽度（旋转后适配）
    height: 100vw !important; // 用视口宽度作为高度
    position: absolute !important;
    top: 50% !important;
    left: 50% !important;
    // 偏移校正（旋转后居中）
    transform: translate(-50%, -50%) rotate(90deg);
  }

  // 单窗口模式横向占满
  .video-container {
    // width: 100vw !important;
    // height: 100vh !important;
    width: 100vh !important;
    height: calc(100vw - 60px) !important;
    display: flex !important;
    justify-content: center !important;
    align-items: center !important;
  }

  // 四窗口模式横向排列
  .video-grid {
    width: 100vh !important;
    height: calc(100vw - 60px) !important;
    // display: flex !important;
    // flex-direction: row !important; // 子项横向排列
    // flex-wrap: nowrap !important; // 不换行（强制单行横向）
    // overflow-x: auto !important; // 横向滚动（超出屏幕时）
    // padding: 20px !important;
    // gap: 10px !important;
    .video-item {
      width: 100%;
      height: 100%;
      margin: 0 !important;
    }
  }

  // 视频播放区域强制横向适配
  .video-play {
    width: 100% !important;
    height: 100% !important;
    object-fit: contain !important; // 保持比例，避免拉伸
  }
  .footer {
    top: 0 !important;
    left: 0 !important;
    right: auto !important; // 取消右侧定位
    bottom: auto !important;
    width: 60px !important; // 左侧宽度
    height: 100vh !important;
    padding: 10px 0 !important; // 垂直方向内边距

    flex-direction: column !important;
    gap: 20px !important; // 控制项之间的间距

    background: #1c1b1b !important;
    z-index: 999999;
    img,
    span {
      // 顺时针旋转90度
      transform: rotate(90deg);
      // 旋转中心设为元素中心（避免偏移）
      transform-origin: center;
      // 调整旋转后元素的间距和大小
      margin: 15px 0; // 垂直方向间距
      width: auto;
      height: auto;
    }
  }

  .video-controls {
    z-index: 999999;
    top: 0 !important; // 距离顶部距离（与footer错开）
    left: 60px !important;
    right: auto !important; // 取消右侧定位
    bottom: auto !important;
    width: 60px !important; // 与footer宽度一致
    height: 100vh !important;
    padding: 10px 0 !important;
    flex-direction: column !important;
    gap: 20px !important; // 控制项之间的间距
    background-color: rgba(0, 0, 0) !important;
    transform: none !important;
    transform-origin: left center !important;
    .sound-control {
      display: flexss;
    }
    .record-control {
      display: flex;
    }
    img {
      width: 30px;
      height: 30px;
    }
    img,
    .resolution-btn {
      // 顺时针旋转90度
      transform: rotate(90deg);
      transform-origin: center;
      // 调整旋转后元素的间距和大小
      margin: 15px 0; // 垂直方向间距
    }
    .canel {
      span {
        transform: rotate(90deg);
        transform-origin: center;
      }
    }
    .clear {
      background: #ffffff;
      span {
        display: flex;
        align-items: center;
        font-size: 12px;
        padding: 2px 5px;
      }
    }
  }
  .footer img {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
::v-deep .el-carousel__arrow {
  // 强制统一定位基准
  top: 50% !important;
  transform: translateY(-50%) !important;
  // 按钮背景色（半透明深色，hover时加深）
  background-color: rgba(0, 0, 0, 0.5) !important;
  // 箭头颜色（白色更醒目）
  color: #fff !important;
  // 增大按钮尺寸
  width: 50px !important;
  height: 50px !important;
  // 字体大小（箭头更大）
  font-size: 20px !important;
  // 圆角（优化外观）
  border-radius: 50px !important;
  // 增加内边距（按钮更饱满）
  padding: 0 15px !important;
  // 确保不被遮挡
  z-index: 100000 !important;

  // 鼠标悬停效果
  &:hover {
    background-color: rgba(0, 0, 0, 0.8) !important;
    // 轻微缩放效果
    transform: scale(1.05);
    transition: all 0.2s ease;
  }
}
</style>
